// miniprogram/pages/campus-edit/campus-edit.js
import WxValidate from '../../utils/WxValidate'
var req = require("../../utils/action.js")
var utils = require("../../utils/util.js")
// 小程序端插入会默认插入openid，云函数插入则不会
const app = getApp()
const classes = {
  '二手闲置': ['教材资料', '化妆用品', '衣物鞋帽', '电子产品', '体育用品', '生活用品'],
  '校园互助': ['校园跑腿', '拼车拼单', '失物寻物', '求助打听'],
  '交友扩列': ['约饭约玩', '组队运动', '心愿墙', '表白墙'],
};

Page({
  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    imageList: [],
    ifShowPopup: false,
    class: -1,
    subclass: -1,
    classText: '',
    columns: [{
        values: Object.keys(classes),
        defaultIndex: 0,
      },
      {
        values: classes['二手闲置'], 
        defaultIndex: 0,
      }
    ],
    submitImagePath:[],
    schoolId:'',
    ifAnonymous:false,
    publishTitle:"本名发布",
    controlOpenStatus:true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let type = options.type
    if(type && type == '5'){
      this.setData({type:5,schoolId:options.schoolId})
    }
    console.log(options)
    this.setData({userInfo:app.globalData.userInfo})
  },
  onChangeAnonymous({ detail }) {
    console.log(detail)
    if(detail){
      this.setData({ ifAnonymous: !this.data.ifAnonymous,publishTitle:'本名发布' })
    }else{
      this.setData({ ifAnonymous: !this.data.ifAnonymous,publishTitle:'随机名称发布' })
    }
  },
  afterRead(event) {
    this.setData({
      imageList: this.data.imageList.concat(event.detail.file)
    })
  },
  onDelete(event) {
    console.log(event.detail.index)
    this.data.imageList.splice(event.detail.index, 1)
    this.setData({
      imageList: this.data.imageList
    })
  },
  onClick(e) {
    this.setData({
      ifShowPopup: true
    })
  },
  onClose() {
    this.setData({
      ifShowPopup: false
    })
  },
  onConfirm(event) {
    const {
      picker,
      value,
      index
    } = event.detail
    console.log(`当前值：${value}, 当前索引：${index}`)
    this.setData({
      classText: value,
      class: index[0],
      subclass: index[1]
    }, () => {
      this.onClose()
    })
  },
  onChange(event) {
    const {
      picker,
      value,
      index
    } = event.detail;
    picker.setColumnValues(1, classes[value[0]]);
  },
  formSubmit(e) {
    let params = e.detail.value,that = this,_url = req.actions.ym+ "file/uploadPicture"
    console.log(params)
    that.setData({
      submitImagePath : []
    })
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0]
      wx.showToast({
        title: error.msg,
        icon: 'none'
      })
      return false
    }
    if(this.data.type != '5'){
      if (this.data.class == -1 || this.data.subClass == -1) {
        wx.showToast({
          title: '请选择帖子分类',
          icon: 'none'
        })
        return false
      }
    }
    
    wx.showLoading({
      title: '发布中',
      mask: true,
    })
    let promiseArr = []
    let fileIDs = []
    // 图片上传
    const imageList = this.data.imageList
    for (let i = 0, len = imageList.length; i < len; i++) {
      let p = new Promise((resolve, reject) => {
        let item = imageList[i].url
        utils.upload(_url,item,'invitation',1,function(res){
          if(res == 'fail'){
            wx.showToast({
              title: '发布失败，请重试',
              icon: 'error'
            })
            reject()
          }else{
            that.data.submitImagePath = that.data.submitImagePath.concat(res)
            resolve()
          }
        })
      })
      promiseArr.push(p)
    }
    Promise.all(promiseArr).then((res) => {
      let _url = req.actions.ym+ "invitation/addInvitation"
      params.img = that.data.submitImagePath && that.data.submitImagePath.length > 0 ? that.data.submitImagePath.join(",") : null
      params.customerId = app.globalData.userInfo.id
      if(this.data.type == '5'){
        params.type = '5'
        params.schoolId = this.data.schoolId
      }else{
        params.type=this.data.class+1,
        params.sub_type=that.data.subclass+1
      }
      params.reportNum=0
      params.likeNum=0
      params.ifAnonymous = this.data.ifAnonymous ? 1 : 0 
      console.log(params)
      utils.myResquest(params,_url,function(res){
        console.log("addInvitation:"+JSON.stringify(res))
        wx.hideLoading({success: (res) => {}})
        if(res.data.code == 200){
          wx.showToast({title: '发布成功！',duration:2000,icon:"success",success:function(){
            setTimeout(function(){wx.navigateBack({delta: -1})},2000)
          }})
        }else{
          wx.showToast({title: res.data.msg,duration:2000,icon:"none",success:function(){}})
        }
       
      })
    })
  },
  initValidate() {
    const rules = {
      nickName: {
        nickName: true,
      },
      phone: {
        tel: true,
      },
      wechat: {
        maxlength: 50
      },
      qq: {
        digits: true
      },
      content: {
        required: true,
      }
    }
    const messages = {
      qq: {
        digits: '请填写有效的qq号或不填',
      },
      content: {
        required: '请填写帖子内容'
      },
    }
    this.WxValidate = new WxValidate(rules, messages)
    this.WxValidate.addMethod('nick_name', (value, param) => {
      return app.globalData.userInfo.if_anonymous || (value.length >= 1 && value.length <= 20);
    }, '请正确填写联系人，不得多于20字')
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function () {
    this.initValidate()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})